<template>
  <div class="download-page">
    <div class="page-header">
      <el-button @click="$router.push('/')" type="primary" plain size="small">
        <el-icon><HomeFilled /></el-icon>
        返回首页
      </el-button>
    </div>

    <el-card class="download-form">
      <template #header>
        <div class="card-header">
          <span>内容下载</span>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px">
        <el-form-item label="平台">
          <el-select v-model="form.platform">
            <el-option label="小红书" value="xiaohongshu" />
            <el-option label="微信公众号" value="wechat" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="下载方式">
          <el-radio-group v-model="form.downloadType">
            <el-radio label="url">单个链接</el-radio>
            <el-radio label="author">作者主页</el-radio>
            <el-radio label="search">关键词搜索</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="URL" v-if="form.downloadType === 'url'">
          <el-input v-model="form.url" placeholder="请输入内容链接" />
        </el-form-item>
        
        <el-form-item label="作者ID" v-if="form.downloadType === 'author'">
          <el-input v-model="form.authorId" placeholder="请输入作者ID" />
        </el-form-item>
        
        <el-form-item label="关键词" v-if="form.downloadType === 'search'">
          <el-input v-model="form.keyword" placeholder="请输入搜索关键词" />
        </el-form-item>
        
        <el-form-item label="筛选条件" v-if="form.downloadType !== 'url'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="form.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最小点赞数">
                <el-input-number v-model="form.minLikes" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="startDownload">开始下载</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="download-progress" v-if="activeDownloads.length">
      <template #header>
        <div class="card-header">
          <span>下载进度</span>
        </div>
      </template>
      
      <div v-for="task in activeDownloads" :key="task.taskId" class="progress-item">
        <div class="progress-info">
          <span>{{ task.fileName }}</span>
          <span>{{ formatProgress(task.progress) }}</span>
        </div>
        <el-progress 
          :percentage="task.progress"
          :status="task.status === 'failed' ? 'exception' : undefined"
        />
        <div class="progress-detail" v-if="task.status === 'downloading'">
          <span>速度: {{ formatSpeed(task.speed) }}</span>
          <span>已下载: {{ formatSize(task.downloadedSize) }} / {{ formatSize(task.totalSize) }}</span>
        </div>
        <div class="error-message" v-if="task.status === 'failed'">
          {{ task.error }}
        </div>
      </div>
    </el-card>
    
    <el-card v-if="activeDownloads.length" class="settings-card">
      <template #header>
        <div class="card-header">
          <span>更新设置</span>
        </div>
      </template>
      <el-form-item label="实时更新">
        <el-switch v-model="autoUpdate" @change="handleAutoUpdateChange"/>
      </el-form-item>
      <el-form-item label="更新间隔(毫秒)">
        <el-input-number 
          v-model="progressInterval"
          :min="1000"
          :max="5000"
          :step="500"
          :disabled="!autoUpdate"
        />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { HomeFilled } from '@element-plus/icons-vue'

const form = ref({
  platform: 'xiaohongshu',
  downloadType: 'url',
  url: '',
  authorId: '',
  keyword: '',
  dateRange: null,
  minLikes: 0
})

const activeDownloads = ref([])
const progressInterval = ref(1000)
const autoUpdate = ref(true)
let progressTimer: number | null = null
const loading = ref(false)

onMounted(() => {
  startProgressUpdate()
})

onUnmounted(() => {
  stopProgressUpdate()
})

function handleAutoUpdateChange(value: boolean) {
  if (value) {
    startProgressUpdate()
  } else {
    stopProgressUpdate()
  }
}

function stopProgressUpdate() {
  if (progressTimer) {
    clearTimeout(progressTimer)
    progressTimer = null
  }
}

function startProgressUpdate() {
  if (!autoUpdate.value) return
  stopProgressUpdate()  // 清除可能存在的定时器
  updateProgress()
}

function adjustInterval(downloads: any[]) {
  const hasActive = downloads.some(
    task => task.status !== 'completed' && task.status !== 'failed'
  )
  
  if (hasActive) {
    progressInterval.value = 1000
  } else {
    progressInterval.value = 5000
  }
}

async function startDownload() {
  loading.value = true
  try {
    const response = await axios.post('/api/download', form.value)
    const { task_id } = response.data
    activeDownloads.value.push({
      taskId: task_id,
      fileName: form.value.url || form.value.authorId || form.value.keyword,
      progress: 0,
      status: 'pending'
    })
  } catch (error) {
    ElMessage.error('下载失败：' + error.message)
  } finally {
    loading.value = false
  }
}

async function updateProgress() {
  for (const task of activeDownloads.value) {
    if (task.status === 'completed' || task.status === 'failed') continue
    
    try {
      const response = await axios.get(`/api/download/progress/${task.taskId}`)
      Object.assign(task, response.data)
    } catch (error) {
      console.error('获取进度失败：', error)
    }
  }

  adjustInterval(activeDownloads.value)
  
  if (autoUpdate.value) {
    progressTimer = setTimeout(updateProgress, progressInterval.value)
  }
}

function formatProgress(progress: number): string {
  return `${progress.toFixed(1)}%`
}

function formatSpeed(speed: number): string {
  if (speed < 1024) return `${speed.toFixed(1)} B/s`
  if (speed < 1024 * 1024) return `${(speed / 1024).toFixed(1)} KB/s`
  return `${(speed / (1024 * 1024)).toFixed(1)} MB/s`
}

function formatSize(size: number): string {
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
  return `${(size / (1024 * 1024)).toFixed(1)} MB`
}
</script>

<style scoped>
.download-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.download-form {
  margin-bottom: 20px;
}

.progress-item {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.progress-detail {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.error-message {
  margin-top: 10px;
  color: #f56c6c;
  font-size: 14px;
}

.page-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-icon {
  margin-right: 4px;
}
</style> 